#!/usr/bin/python -t

import os
from content import Content
import re

class nMedia:
	def __init__(self,debug=False):
		self.Content = Content(debug=debug)
		self.load_plugins()
		
		self.IMDB_URL = re.compile("imdb.com/title[/?](?P<url>[a-zA-Z0-9\+\-]*)",re.IGNORECASE)
		
	def load_plugins(self):
		self.plugins = {}
		for x in os.listdir("scrapers"):
			if os.path.splitext(x)[1] != ".py":
				continue
			print "Loading",x
			script = open(os.path.join("scrapers",x)).read()
			exec(script) in globals()
			s = Scraper()
			self.plugins[s.name] = s
			
		#Standards for searching:
		self.Movie = self.plugins["TheMovieDB"]
		
	def CheckUrls(self,contentId):
		#Checks urls for contentId and auto adds if possible.
		x = self.Content.conn.execute("SELECT url FROM Urls WHERE contentId=?",(contentId,)).fetchmany()
		#print "Checking urls for",contentId
		imdb = None
		themovieDb = None
		for row in x:
			match = self.IMDB_URL.findall(row[0])
			if match:
				imdb = match[0]
			
			if row[0].find("themoviedb") > 0:
				themovieDb = True
		
		if imdb and not themovieDb:
			#print "Resolving imdb link",imdb
			url = self.plugins["TheMovieDB"].IMDBLookup(imdb)
			if url:
				#print "Url resolved to id:",url
				self.Content.AddUrl(contentId,url)
		
	def UpdateDetails(self,contentId):
		thetvdb = None
		imdb = None
		themoviedb = None
		print "Updating details"
		
		for url in self.Content.conn.execute("SELECT url FROM Urls WHERE contentId=?",(contentId,)).fetchmany():
			url = url[0].lower()
			if url.find("thetvdb.com") > 0:
				thetvdb = url
			if url.find("themoviedb") > 0:
				themoviedb = url
			if url.find("imdb.com") > 0:
				imdb = url
		if (themoviedb):
			print "TheMovieDB - Update details %s" % url
			self.Content.UpdateDetails(contentId,self.plugins["TheMovieDB"].GetDetails(url))
			return
		if (thetvdb):
			print "TheTvDB - Update details %s" % url
			self.Content.UpdateDetails(contentId,self.plugins["TheTvDB"].GetDetails(url))
			return
		DIE
		
	def MovieSearch(self,name,year=None):
		return self.Movie.Search(name,year)
		
	def MovieDetails(self,id):
		return self.Movie.GetDetails(id)
